<template>
  <div class="countDown">{{ days }}天{{ hours }}:{{ mins }}:{{ seconds }}</div>
</template>
<script>
export default {
  name: "countDown",
  props: {
    //剩余时间
    time: {
      type: [Number, String],
      default: 0,
    },
    //是以秒(false)为单位or毫秒(ture)
    isMilliSecond: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      days: "",
      hours: "",
      mins: "",
      seconds: "",
      timer: null, //定时器
      curTime: 0,
    };
  },
  computed: {
    //将时间转化为秒,"+this.time"是将传来的格式转化为数字
    duration: {
      get() {
        return +this.time / 1000;
      },
    },
  },
  watch: {
    //剩余时间变化就继续倒计时减一秒
    duration() {
      this.countDowns();
    },
  },
  mounted() {
    this.countDowns(); //进入就开始计时
  },
  methods: {
    //开始倒计时
    countDowns() {
      this.getTime(this.duration);
    },
    //获得剩余时间开始倒计时，使用setTimeout+递归的方法
    getTime(duration) {
      this.timer && clearTimeout(this.timer);
      if (duration < 0) {
        return;
      }
      const { dd, hh, mm, ss } = this.durationFormatter(duration);
      this.days = dd || 0;
      this.hours = hh || 0;
      this.mins = mm || 0;
      this.seconds = ss || 0;
      this.timer = setTimeout(() => {
        this.getTime(duration - 1);
      }, 1000);
    },
    // timeFormat(time){
    // }
    durationFormatter(time) {
      var dd = parseInt(time / 60 / 60 / 24);
      dd = dd < 10 ? "0" + dd : dd;
      var hh = parseInt((time / 60 / 60) % 24);
      hh = hh < 10 ? "0" + hh : hh;
      var mm = parseInt((time / 60) % 60);
      mm = mm < 10 ? "0" + mm : mm;
      var ss = parseInt(time % 60);
      ss = ss < 10 ? "0" + ss : ss;
      return { dd, hh, mm, ss };
    },
  },
};
</script>
<style lang="less" scoped>
.countDown {
  display: inline-block;
}
</style>